package com.captain.special.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.List;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/3/22 9:05
 */
public class 两数相加02 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //同时循环两个链表 , 两个链表都为空时, 退出循环 , 如何记录最后相加的值 ? 处理最后的计算
        int n = 0;
        ListNode dummy = new ListNode();
        ListNode cur = dummy;

        for (; ; ) {
            //退出条件
            if (l1 == null && l2 == null) {
                break;
            }
            int sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + n;
            //当前的值
            cur.next = new ListNode(sum % 10);
            cur = cur.next;

            //复位n的值
            n = sum / 10;
            l1 = (l1 == null ? null : l1.next);
            l2 = (l2 == null ? null : l2.next);
        }
        //最后还存在值
        if (n != 0) {
            cur.next = new ListNode(n);
        }
        return dummy.next;
    }
}
